#include "heartRequest.h"
#include "adLogic.h"
void pearsCmd(cJSON* cmdList){
    //判断是否是数组
   if (!cJSON_IsArray(cmdList))
   {        
        return;
   }
   //获取数组的size
   int size = cJSON_GetArraySize(cmdList);
   for (int i = 0; i < size; i++)
   {
        //获取对应的元素
        cJSON *item= cJSON_GetArrayItem(cmdList,i);
        int cmd =item->valueint;//获取对应的具体的操作
        switch (cmd)
        {
        case 1 :
            //关机
            //system(" echo yaosang | sudo -S shutdown -h now "); 
        break;
        case 2 :
            //重启   reboot
            //system("echo yaosang | sudo -S reboot");
        break;
            case 3 :
            //a检查更新
        break; 
        default:
        break;
        }
   }
}
//请求的回调
//1.获取当前请求的内容
//2.如果请求成功解析里面的指令集 和 广告列表
size_t heartCallback(void *contents, size_t size, size_t nmemb, void *userp) {
    size_t realsize = size * nmemb;
    // 这里可以处理获取到的数据，比如存储到文件或者其他操作
    char * result = (char *)contents;
    printf("%s\n",result);
    cJSON *jsonstr= cJSON_Parse(result);
    if(jsonstr!=NULL){
        cJSON *successRoot = cJSON_GetObjectItemCaseSensitive(jsonstr,"success");
        
        cJSON *messageRoot = cJSON_GetObjectItemCaseSensitive(jsonstr,"message");
        
        if(!cJSON_IsTrue(successRoot)){

            printf("%s\n",messageRoot->valuestring) ;   
            return -1; 
        }
        
        cJSON *dataRoot = cJSON_GetObjectItemCaseSensitive(jsonstr,"data");
        cJSON *adList = cJSON_GetObjectItemCaseSensitive(dataRoot,"ad_list");
        cJSON *cmdList = cJSON_GetObjectItemCaseSensitive(dataRoot,"cmd_list");
        //正常去解析指令集
        //cmdList取出指令去执行
        pearsCmd(cmdList);
        //解析广告列表
        handleAdList(adList);
    }
   
    return realsize;
}


void sendHeartRequest(char* ip,char* sn){
    //1.发送请求
    char *url ="http://%s/config.json?sn=%s";
    char * realUrl= calloc(1,100);
    sprintf(realUrl,url,ip,sn);
    printf("request address:%s\n",realUrl);

    //发送一个get请求
    //http://ip/config.json?sn=1205556
    sendGetRequest(realUrl,heartCallback);

}

